<template>
	<view :style="colorStyle">
		<form @submit="formSubmit">
			<view class='addAddress'>
				<view class='list'>
					<view class='item acea-row row-between-wrapper'>
						<view class='name'>姓名</view>
						<input type='text' placeholder='请输入姓名' name='name' v-model="formData.name"
							placeholder-class='placeholder'></input>
					</view>
					<view class='item acea-row row-between-wrapper'>
						<view class='name'>联系电话</view>
						<input type='number' placeholder='请输入联系电话' name="phone" v-model="formData.phone"
							placeholder-class='placeholder' pattern="\d*"></input>
					</view>
					<view class='item acea-row row-between-wrapper'>
						<view class='name'>代理级别</view>
						<picker style="text-align: right;" @change="bindPickerChange" :value="indexPicker"
							:range="levelType" range-key="name">
							<view style="padding: 20rpx;background-color: white;">{{ levelType[indexPicker].name }}
							</view>
						</picker>
						<!-- 	<radio-group name="type" @change="radioChange">
							<radio v-for="(item,index) in formModel.type" :value="index"
								:checked="(index == formData.type ? true : false)">{{item}}</radio>
						</radio-group> -->
					</view>

					<!-- <view class='item acea-row row-between-wrapper'>
						<view class='name'>省</view>
						<view class="address">
							<picker mode="selector" @change="bindRegionChange" data-name="province"
								@columnchange="bindMultiPickerColumnChange" :value="valueRegion"
								:range="formModel.province" range-key="name">
								<view class='acea-row'>
									<view class="picker">{{formText.province}}</view>
								</view>
							</picker>
						</view>
					</view>
					<view class='item acea-row row-between-wrapper'>
						<view class='name'>市</view>
						<view class="address">
							<picker mode="selector" @change="bindRegionChange" data-name="city"
								@columnchange="bindMultiPickerColumnChange" :value="valueRegion" :range="formModel.city"
								range-key="name">
								<view class='acea-row'>
									<view class="picker">{{formText.city}}</view>
								</view>
							</picker>
						</view>
					</view>
					<view class='item acea-row row-between-wrapper'>
						<view class='name'>区</view>
						<view class="address">
							<picker mode="selector" @change="bindRegionChange" data-name="district"
								@columnchange="bindMultiPickerColumnChange" :value="valueRegion"
								:range="formModel.district" range-key="name">
								<view class='acea-row'>
									<view class="picker">{{formText.district}}</view>
								</view>
							</picker>
						</view>
					</view>
					<view class='item acea-row row-between-wrapper'>
						<view class='name'>镇</view>
						<view class="address">
							<picker mode="selector" @change="bindRegionChange" data-name="town"
								@columnchange="bindMultiPickerColumnChange" :value="valueRegion" :range="formModel.town"
								range-key="name">
								<view class='acea-row'>
									<view class="picker">{{formText.town}}</view>
								</view>
							</picker>
						</view>
					</view> -->
					<view class='item acea-row row-between-wrapper'>
						<view class='name'>所在地区</view>
						<view class="address">
							<picker mode="multiSelector" @change="bindRegionChange"
								@columnchange="bindMultiPickerColumnChange" :value="valueRegion" :range="multiArray">
								<view class='acea-row'>
									<view class="picker">{{region[0]}}，{{region[1]}}，{{region[2]}}，{{region[3]||''}}
									</view>
									<view class='iconfont icon-dizhi fontcolor'></view>
								</view>
							</picker>
						</view>
					</view>
					<view class='item acea-row row-between-wrapper'>
						<view class='name'>详细地址</view>
						<view class="input-icon">
							<textarea auto-height='true' placeholder='请填写具体地址' name='address'
								placeholder-class='placeholder' v-model="formData.address" />


							<view style="width: 270rpx;" class='iconfont icon-dizhi fontcolor' @click="getLocation">
								获取位置</view>
						</view>
					</view>

					<view class='item acea-row row-between-wrapper'>
						<view class='name'>邀请码</view>
						<input type='text' placeholder='注意大小写' v-model="formData.invitation_code"
							placeholder-class='placeholder'></input>
					</view>
				</view>
				<button class='keepBnt bg-color' form-type="submit">立即保存</button>
			</view>
		</form>
		<!-- #ifdef MP -->
		<!-- <authorize @onLoadFun="onLoadFun" :isAuto="isAuto" :isShowAuth="isShowAuth" @authColse="authColse"></authorize> -->
		<!-- #endif -->
		<!-- #ifndef MP -->
		<home></home>
		<!-- #endif -->
	</view>
</template>

<script>
	import {
		getProxyApplyForm,
		getProxyApply
	} from '@/api/proxy.js';
	import {
		getCity,
	} from '@/api/api.js';
	import {
		getUserInfo
	} from '@/api/user.js';
	import {
		toLogin
	} from '@/libs/login.js';
	import {
		mapGetters
	} from "vuex";

	// #ifdef MP
	import authorize from '@/components/Authorize';
	// #endif
	import home from '@/components/home';
	import colors from '@/mixins/color.js';
	export default {
		components: {
			// #ifdef MP
			authorize,
			// #endif
			home,
		},
		mixins: [colors],
		data() {
			return {
				regionDval: ['浙江省', '杭州市', '滨江区'],
				cartId: '', //购物车id
				pinkId: 0, //拼团id
				couponId: 0, //优惠券id
				id: 0, //地址id
				cityData: {},
				formModel: {
					type: {
						1: '省',
						2: '市',
						3: '区',
						4: '镇'
					},
					province: [],
					city: [],
					district: [],
					town: [],
				},
				formText: {
					province: '请选择...',
					city: '请选择...',
					district: '请选择...',
					town: '请选择...',
				},
				formData: {
					is_default: false,
					type: 1,
					address: '',
					invitation_code: '',
					name: '',
					phone: ''
				}, //地址详情
				region: ['省', '市', '区', '镇'],
				valueRegion: [0, 0, 0, 0],
				isAuto: false, //没有授权的不会自动授权
				isShowAuth: false, //是否隐藏授权
				district: [],
				multiArray: [],
				multiIndex: [0, 0, 0, 0],
				cityId: 0,
				defaultRegion: ['广东省', '广州市', '番禺区'],
				defaultRegionCode: '110101',
				news: '',
				noCoupon: 0,
				userAddress: {},
				userInfo: {},
				levelType: [],
				indexPicker: 0,
			};
		},
		computed: mapGetters(['isLogin']),
		watch: {
			isLogin: {
				handler: function(newV, oldV) {
					if (newV) {
						this.getPageData();
					}
				},
				deep: true
			}
		},
		onLoad(options) {
			if (this.isLogin) {
				this.cartId = options.cartId || '';
				this.pinkId = options.pinkId || 0;
				this.couponId = options.couponId || 0;
				this.id = options.id || 0;
				this.noCoupon = options.noCoupon || 0;
				this.news = options.new || '';
				uni.setNavigationBarTitle({
					title: options.id ? '申请代理' : '申请代理'
				});
				this.getPageData();
				this.getCityList()
				this.getUserInfo()
				// this.getCityProvince();
				// this.getCityCity();
				// this.getCityDistrict();
				// this.getCityTown();
			} else {
				toLogin();
			}
		},
		methods: {
			bindPickerChange: function(e) {
				this.indexPicker = e.detail.value;
			},
			getUserInfo: function() {
				let that = this;
				getUserInfo().then(res => {
					if (res.data.proxy_level) {
						let arr = []
						for (let i in res.data.proxy_level) {
							let obj = {
								name: res.data.proxy_level[i]
							}
							arr.push(obj)
						}
						this.levelType = arr
					}
					that.userInfo = res.data

				});
			},
			// 回去地址数据
			getCityList: function() {
				uni.showLoading({
					title: '加载中',
					mask: true
				});

				let that = this;
				getCity().then(res => {

					this.district = res.data
					that.initialize();
				})
			},
			initialize: function() {
				let that = this,
					province = [],
					city = [],
					area = [],
					town = [];
				if (that.district.length) {
					let cityChildren = that.district[0].c || [];
					let areaChildren = cityChildren.length ? (cityChildren[0].c || []) : [];
					let townChildren = areaChildren.length ? (areaChildren[0].c || []) : []
					that.district.forEach(function(item) {
						province.push(item.n);
					});
					cityChildren.forEach(function(item) {
						city.push(item.n);
					});
					areaChildren.forEach(function(item) {
						area.push(item.n);
					});
					townChildren.forEach(function(item) {
						town.push(item.n);
					});
					this.multiArray = [province, city, area, town]
				}
				uni.hideLoading()
			},
			bindMultiPickerColumnChange: function(e) {
				console.log(e, 'bindMultiPickerColumnChange')
				let that = this,
					column = e.detail.column,
					value = e.detail.value,
					currentCity = this.district[value] || {
						c: []
					},
					multiArray = that.multiArray,
					multiIndex = that.multiIndex;
				multiIndex[column] = value;
				switch (column) {
					case 0:
						let areaList = currentCity.c[0] || {
							c: []
						};
						let townList = areaList.c[0] || {
							c: []
						}
						console.log(townList, 'townList')
						multiArray[1] = currentCity.c.map((item) => {
							return item.n;
						});
						multiArray[2] = areaList.c.map((item) => {
							return item.n;
						});
						multiArray[3] = townList.c.map((item) => {
							return item.n;
						});

						break;
					case 1:
						let cityList = that.district[multiIndex[0]].c[multiIndex[1]].c || [];
						let town2 = that.district[multiIndex[0]].c[multiIndex[1]].c[multiIndex[2]].c || [];
						console.log(town2, 'town2town2')
						multiArray[2] = cityList.map((item) => {
							return item.n;
						});
						multiArray[3] = town2.map((item) => {
							return item.n;
						});
						break;
					case 2:
						let town = that.district[multiIndex[0]].c[multiIndex[1]].c[multiIndex[2]].c || [];
						multiArray[3] = town.map((item) => {
							return item.n;
						});
						break;
				}
				console.log(multiArray, 'multiArraymultiArraymultiArray')
				// #ifdef MP || APP-PLUS
				this.$set(this.multiArray, 0, multiArray[0]);
				this.$set(this.multiArray, 1, multiArray[1]);
				this.$set(this.multiArray, 2, multiArray[2]);
				this.$set(this.multiArray, 3, multiArray[3]);
				// #endif
				// #ifdef H5 
				this.multiArray = multiArray;
				// #endif



				this.multiIndex = multiIndex
				// this.setData({ multiArray: multiArray, multiIndex: multiIndex});
			},
			getPageData: function() {
				let that = this;
				getProxyApplyForm().then(res => {
					console.log(res.data, 'res.data')
					if (res.data.form_data.province) {
						let {
							province,
							city,
							district,
							town,
							id,
							province_id,
							city_id,
							district_id,
							town_id
						} = res.data.form_data
						console.log('进来了')
						let region = [province, city, district, town];
						that.$set(that, 'region', region);

						that.formData = {
							...that.formData,
							province,
							city,
							district,
							town,
							id,
							province_id,
							city_id,
							district_id,
							town_id
						}
					}
					that.formData = {
						...that.formData,
						address: res.data.form_data.address,
						invitation_code: '',
						phone: res.data.form_data.phone,
						name: res.data.form_data.name,
						longitude: res.data.form_data.longitude,
						latitude: res.data.form_data.latitude,
					}

					that.index = res.data.form_data.type
					that.$set(that, 'userAddress', res.data);
					that.cityId = res.data.city_id
				});
			},
			getCityProvince() {
				let that = this;
				getCityProvince().then(res => {
					that.cityData.province = res.data;
					that.formModel.province = that.cityData.province;
					console.log(that.formModel);
				})
			},
			getCityCity() {
				let that = this;
				getCityCity().then(res => {
					that.cityData.city = res.data;
				})
			},
			getCityDistrict() {
				let that = this;
				getCityDistrict().then(res => {
					that.cityData.district = res.data;
				})
			},
			getCityTown() {
				let that = this;
				getCityTown().then(res => {
					that.cityData.town = res.data;
				})
			},

			pickerArray(data, name) {
				let item = [];
				for (let i in data) {
					item.push(data[i][name]);
				}
				return item;
			},
			// 
			radioChange(e) {
				let that = this;
				this.formData.type = e.target.value;
			},
			// bindRegionChange: function(e) {
			// 	let value = e.detail.value,
			// 		name = e.currentTarget.dataset.name;
			// 	this.formData[name] = this.formModel[name][value]['city_id'];
			// 	this.formText[name] = this.formModel[name][value]['name'];
			// 	switch (e.currentTarget.dataset.name) {
			// 		case 'province':
			// 			this.formText.city = '请选择...';
			// 			this.formText.district = '请选择...';
			// 			this.formText.town = '请选择...';
			// 			this.formModel.city = this.cityData.city[this.formData.province];
			// 			this.formModel.district = [];
			// 			this.formModel.town = [];
			// 			break;
			// 		case 'city':
			// 			this.formText.district = '请选择...';
			// 			this.formText.town = '请选择...';
			// 			this.formModel.district = this.cityData.district[this.formData.city];
			// 			this.formModel.town = [];
			// 			break;
			// 		case 'district':
			// 			this.formText.town = '请选择...';
			// 			this.formModel.town = this.cityData.town[this.formData.district];
			// 			break;
			// 		case 'town':
			// 			break;
			// 	}
			// }, 
			bindRegionChange: function(e) {
				console.log(e, 'eeeeeeeeeeee')

				let multiIndex = this.multiIndex,
					province = this.district[multiIndex[0]] || {
						c: []
					},
					city = province.c[multiIndex[1]] || {
						v: 0
					},
					district = city.c[multiIndex[2]] || {
						v: 0
					},
					town = district.c[multiIndex[3]] || {
						v: 0
					},
					multiArray = this.multiArray,
					value = e.detail.value;


				this.region = [multiArray[0][value[0]], multiArray[1][value[1]], multiArray[2][value[2]], multiArray[3]
					[value[3]]
				]
				console.log(town, 'town')
				console.log(multiIndex, 'multiIndex')
				console.log(district.c, 'districtdistrict')

				this.formData = Object.assign(this.formData, {
					province: province.n,
					city: city.n,
					district: district.n,
					town: town.n,
					province_id: province.v,
					city_id: city.v,
					district_id: district.v,
					town_id: town.v
				});

				this.valueRegion = [0, 0, 0, 0]
				this.initialize();
			},
			getLocation() {
				console.log('123sadasd')
				let that = this;
				uni.chooseLocation({
					success: function(res) {
						console.log(res, 'rrrrrr')
						that.formData.longitude = res.longitude;
						that.formData.latitude = res.latitude;
						that.formData.address = res.name
						console.log(that.formData, 'that.formData')
					}
				})
			},
			/**
			 * 提交用户添加地址
			 */
			formSubmit: function(e) {
				let that = this,
					value = e.detail.value;

				if (!value.name.trim()) return that.$util.Tips({
					title: '请填写收货人姓名'
				});
				if (!value.phone) return that.$util.Tips({
					title: '请填写联系电话'
				});
				if (!/^1(3|4|5|7|8|9|6)\d{9}$/i.test(value.phone)) return that.$util.Tips({
					title: '请输入正确的手机号码'
				});
				value.id = that.id;
				value = Object.assign(value, this.formData, {
					type: (this.indexPicker * 1) + 1
				});


				uni.showLoading({
					title: '保存中',
					mask: true
				})
				getProxyApply(value).then(res => {
					if (that.id)
						that.$util.Tips({
							title: '修改成功',
							icon: 'success'
						});
					else
						that.$util.Tips({
							title: '添加成功',
							icon: 'success'
						});
					setTimeout(function() {
						if (that.cartId) {
							let cartId = that.cartId;
							let pinkId = that.pinkId;
							let couponId = that.couponId;
							that.cartId = '';
							that.pinkId = '';
							that.couponId = '';
							uni.navigateTo({
								url: '/pages/users/order_confirm/index?new=' + that.news +
									'&cartId=' + cartId + '&addressId=' + (that.id ? that.id :
										res.data.id) + '&pinkId=' + pinkId + '&couponId=' +
									couponId +
									'&noCoupon=' + that
									.noCoupon
							});
						} else {
							// #ifdef H5
							return history.back();
							// #endif
							// #ifndef H5
							return uni.navigateBack({
								delta: 1,
							})
							// #endif
						}
					}, 1000);
				}).catch(err => {
					return that.$util.Tips({
						title: err
					});
				})
			},
		}
	}
</script>

<style scoped lang="scss">
	.fontcolor {
		color: var(--view-theme);
	}

	.addAddress .list {
		background-color: #fff;
	}

	.addAddress .list .item {
		padding: 30rpx;
		border-top: 1rpx solid #eee;
	}

	.addAddress .list .item .name {
		width: 195rpx;
		font-size: 30rpx;
		color: #333;
	}

	.addAddress .list .item .address {
		// width: 412rpx;
		flex: 1;
		margin-left: 20rpx;
	}

	.addAddress .list .item input {
		width: 475rpx;
		font-size: 30rpx;
	}

	.addAddress .list .item .input-icon {
		width: 475rpx;
		display: flex;
	}

	.addAddress .list .item .input-icon input {
		flex: 1;
		width: auto;
	}

	.addAddress .list .item .placeholder {
		color: #ccc;
	}

	.addAddress .list .item picker {
		width: 475rpx;
	}

	.addAddress .list .item picker .picker {
		width: 410rpx;
		font-size: 30rpx;
	}

	.addAddress .list .item picker .iconfont {
		font-size: 43rpx;
	}

	.addAddress .default {
		padding: 0 30rpx;
		height: 90rpx;
		background-color: #fff;
		margin-top: 23rpx;
	}

	.addAddress .default checkbox {
		margin-right: 15rpx;
	}

	.addAddress .keepBnt {
		width: 690rpx;
		height: 86rpx;
		border-radius: 50rpx;
		text-align: center;
		line-height: 86rpx;
		margin: 50rpx auto;
		font-size: 32rpx;
		color: #fff;
	}

	.addAddress .wechatAddress {
		width: 690rpx;
		height: 86rpx;
		border-radius: 50rpx;
		text-align: center;
		line-height: 86rpx;
		margin: 0 auto;
		font-size: 32rpx;
		color: var(--view-theme);
		border: 1px solid var(--view-theme);
	}
</style>
